package org.example.day05;

/**
 * 第二章节2.2.8:细化验证3个结论
 *      结论1：当多个线程同时执行 synchronized(x){} 同步代码块时，呈现同步效果
 *      - case1: 多个线程使用同一个监视器,即对象锁，可以达到线程同步
 *      - case2: 多个线程使用不同的监视器，无法达到同步
 */
public class MyThread {
    public void testMethod(MyObject object){
        synchronized (object){
            try {
                System.out.println("lock Time = " + System.currentTimeMillis() + " ThreadName = " + Thread.currentThread().getName());
                Thread.sleep(2000);
                System.out.println("unlock Time = " + System.currentTimeMillis() + " ThreadName = " + Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //case1
//    public static void main(String[] args) {
//        MyThread m1 = new MyThread();
//        MyObject mo = new MyObject();
//        ThreadA ta = new ThreadA(m1, mo);
//        ta.setName("A");
//        ta.start();
//        ThreadB tb = new ThreadB(m1, mo);
//        tb.setName("B");
//        tb.start();
//    }

    //case2
    public static void main(String[] args) {
        MyThread m1 = new MyThread();
        MyObject mo1 = new MyObject();
        MyObject mo2 = new MyObject();
        ThreadA ta = new ThreadA(m1, mo1);
        ta.setName("A");
        ta.start();
        ThreadB tb = new ThreadB(m1, mo2);
        tb.setName("B");
        tb.start();
    }
}

class MyObject{

}

class ThreadA extends Thread{
    private MyThread m1;
    private MyObject mo;

    public ThreadA(MyThread m1, MyObject mo) {
        this.m1 = m1;
        this.mo = mo;
    }

    @Override
    public void run() {
        m1.testMethod(mo);
    }
}

class ThreadB extends Thread{
    private MyThread m1;
    private MyObject mo;

    public ThreadB(MyThread m1, MyObject mo) {
        this.m1 = m1;
        this.mo = mo;
    }

    @Override
    public void run() {
        m1.testMethod(mo);
    }
}